package com.book.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.core.domain.BookCategories;
import com.book.core.domain.Books;
import com.book.core.query.BookQuery;
import com.book.core.vo.PageVO;
import com.book.repository.BooksMapper;
import com.book.service.BookCategoriesService;
import com.book.service.BooksService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hongmizfb
 * @description 针对表【books(图书表)】的数据库操作Service实现
 * @createDate 2025-05-07 16:18:08
 */
@Service
@RequiredArgsConstructor
public class BooksServiceImpl extends ServiceImpl<BooksMapper, Books>
        implements BooksService {
    private final BookCategoriesService bookCategoriesService;

    @Override
    public PageVO<Books> getBookPage(BookQuery bookQuery) {
        Integer categoryId = bookQuery.getCategoryId();
        BookCategories byId = bookCategoriesService.getById(categoryId);
        List<Integer> categoryIds = null;
        if (byId != null) {
            categoryIds = bookCategoriesService.getChildrenList(categoryId, byId.getLevel()).stream().map(BookCategories::getCategoryId).collect(Collectors.toList());
        }
        String keyword = bookQuery.getKeyword();
        Page<Books> page = lambdaQuery()
                .eq(StrUtil.isNotBlank(keyword), Books::getTitle, keyword)
                .or()
                .like(StrUtil.isNotBlank(keyword), Books::getTitle, keyword)
                .or()
                .like(StrUtil.isNotBlank(keyword), Books::getSubtitle, keyword)
                .or()
                .like(StrUtil.isNotBlank(keyword), Books::getAuthor, keyword)
                .in(categoryIds != null, Books::getCategoryId, categoryIds)
                .page(bookQuery.toMpPage());
        return PageVO.of(page, Books.class);
    }
}




